package app.qrcode.browser.chat.activities

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import app.qrcode.browser.chat.model.Model
import app.qrcode.browser.chat.MyApplication.Companion.context
import app.qrcode.browser.chat.R
import app.qrcode.browser.chat.model.bean.UserInfo
import com.hyphenate.EMCallBack
import com.hyphenate.chat.EMClient
import kotlinx.android.synthetic.main.activity_main.*
import java.lang.Exception
import kotlin.concurrent.thread


class MainActivity : AppCompatActivity() {
    private lateinit var prefs: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        isLogin()
        initPreference()
        initView()
    }
    private fun isLogin() {
        Model.executors.execute {
            if (EMClient.getInstance().isLoggedInBefore) {
                val account = Model.userAccountDao.getAccountByHxId(EMClient.getInstance().currentUser)
                Log.w("cdm", "MainActivity.isLogin -> $account")
               if (account!=null) {
                   Model.loginSuccess(account)
                    val intent = Intent(this, Main::class.java)
                    startActivity(intent)
                }
            }
        }

    }

    private fun initView() {
        dengLuBtn.setOnClickListener {
            Log.w("cdm", "MainActivity.initView -> 用户点击了登录按钮")
            signIn()
        }
        zhuCheBtn.setOnClickListener {
            Log.w("cdm", "MainActivity.initView -> 用户点击了注册按钮")
            signUp()
        }

    }

    private fun signUp() {
        Model.executors.execute{
            try {
                EMClient.getInstance().createAccount(
                    editTextTextEmailAddress.text.toString().trim(),
                    editTextTextPassword.text.toString().trim()
                )
                Log.w("cdm", "MainActivity.initView ->注册成功")//同步方法

                runOnUiThread {
                    Toast.makeText(context,"注册成功,请重新输入密码并登录",Toast.LENGTH_SHORT).show()
                    editTextTextPassword.text.clear()
                }
            } catch (e: Exception) {
                Log.w("cdm", "MainActivity.signUp -> 注册失败")

                runOnUiThread {
                    Toast.makeText(context,"注册失败",Toast.LENGTH_SHORT).show()
                    editTextTextEmailAddress.text.clear()
                    editTextTextPassword.text.clear()
                }
            }
        }
    }

    private fun signIn() {
        if (editTextTextEmailAddress.text.toString() == "" || editTextTextPassword.text.toString() == "") {
            runOnUiThread { Toast.makeText(context,"登录失败,用户名和密码不能为空！",Toast.LENGTH_SHORT).show() }
            return
        }
        EMClient.getInstance().login(editTextTextEmailAddress.text.toString().trim(), editTextTextPassword.text.toString().trim(), object : EMCallBack {
            //回调
            override fun onSuccess() {
                Model.loginSuccess(UserInfo(null,editTextTextEmailAddress.text.toString().trim(),null,null))
                EMClient.getInstance().groupManager().loadAllGroups()
                EMClient.getInstance().chatManager().loadAllConversations()
                Log.w("cdm", "登录聊天服务器成功！")
                Model.userAccountDao.addAccount(UserInfo(null,editTextTextEmailAddress.text.toString(),null,null))

                runOnUiThread {
                    Toast.makeText(context,"登录成功",Toast.LENGTH_SHORT).show()
                    editTextTextEmailAddress.text.clear()
                    editTextTextPassword.text.clear()
                }
                val editor=prefs.edit()
                val account=editTextTextEmailAddress.text.toString()
                val password=editTextTextPassword.text.toString()
                if (checkBox.isChecked) {
                    editor.apply{
                        putBoolean("remember_password", true)
                        putString("account", account)
                        putString("password",password)
                    }
                    }else editor.clear()
                editor.apply()
                val intent = Intent(this@MainActivity, AskChatActivity::class.java)
                startActivity(intent)
            }

            override fun onProgress(progress: Int, status: String) {}
            override fun onError(code: Int, message: String) {
                Log.w("cdm", "登录聊天服务器失败！")

                runOnUiThread {
                    Toast.makeText(context,"登录失败",Toast.LENGTH_SHORT).show()
                    editTextTextEmailAddress.text.clear()
                    editTextTextPassword.text.clear()
                }
            }
        })
    }

    private fun initPreference() {
        this.prefs = getPreferences(Context.MODE_PRIVATE)
        val isRemember = prefs.getBoolean("remember_password", false)
        if (isRemember) {
            val account = prefs.getString("account", "")
            val password = prefs.getString("password", "")
            editTextTextEmailAddress.setText(account)
            editTextTextPassword.setText(password)
            checkBox.isChecked=true
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        thread { EMClient.getInstance().logout(true); }
    }
}